package com.lysj.print.print.feignImpl;

import com.lysj.admin.common.food.domain.OrderItemVo;
import com.lysj.admin.common.print.domain.PrintOrderVo;
import com.lysj.admin.common.print.feign.PrinterServiceFeign;
import com.lysj.admin.utils.constant.CommonConstant;
import com.lysj.admin.utils.json.JacksonUtil;
import com.lysj.admin.utils.web.ParamUtil;
import com.lysj.print.print.domain.AreaDetail;
import com.lysj.print.print.domain.PrintArea;
import com.lysj.print.print.domain.Printer;
import com.lysj.print.print.domain.PrinterRotation;
import com.lysj.print.print.service.AreaDetailService;
import com.lysj.print.print.service.PrintAreaService;
import com.lysj.print.print.service.PrinterRotationService;
import com.lysj.print.print.service.PrinterService;
import com.lysj.print.print.util.PrinterUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 11:04 2019/3/22
 * @ Description:
 **/
@RestController
public class PrintServiceFeignImpl implements PrinterServiceFeign {


    private static final String URL = "http://api.feieyun.cn/Api/Open/";//不需要修改
    private static final String USER = "691617970@qq.com";//*必填*：账号名
    private static final String UKEY = "DV3S6mU3hw8aZ4AV";//*必填*: 注册账号后生成的UKEY
    private static final String SN = "920508225";//*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API


    @Resource
    private AreaDetailService areaDetailService;

    @Resource
    private PrintAreaService printAreaService;

    @Resource
    private PrinterService printerService;

    @Resource
    private PrinterRotationService printerRotationService;

    /*
     * @author drj
     * @date 2019-04-02 15:50
     * @Description :用户下单打印
     */
    @Override
    public void acceptOrderInfo(@RequestBody PrintOrderVo printOrderVo) {



        String content;
        content = "<CB>测试打印</CB><BR>";
        content += "名称　　　　　 单价  数量 金额<BR>";
        content += "--------------------------------<BR>";
        for (OrderItemVo itemVo : printOrderVo.getOrderItemVoList()) {
            content += itemVo.getName() + "　　　　　　 " + itemVo.getUnitPrice() + "    "
                    + itemVo.getAmount() + "   " + itemVo.getTolPrice() + "<BR>";
        }
        System.out.println(content);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", SN));
        nvps.add(new BasicNameValuePair("content", content.toString()));
        nvps.add(new BasicNameValuePair("times", "1"));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map<String, Object> map = JacksonUtil.toObjectMap(result);
        if (map.get("ret").equals(0)) {
            System.out.println("打印成功");
        } else {
            System.out.println("打印失败");
        }


        //默认打印 2次
        defaultPrint(printOrderVo);
        //分区打印
        areaPrint(printOrderVo.getOrderItemVoList());
    }


    /*
     * @author drj
     * @date 2019-04-02 15:55
     * @Description :退菜
     */
    @Override
    public void retreatFood(@RequestBody List<OrderItemVo> orderItemVoList) {
        areaPrint(orderItemVoList);
    }

    /*
     * @author drj
     * @date 2019-04-02 16:00
     * @Description :结单
     */
    @Override
    public void closeOrder(@RequestBody PrintOrderVo printOrderVo) {
        defaultPrint(printOrderVo);
    }


    //默认打印
    private void defaultPrint(PrintOrderVo printOrderVo) {
        Printer deFaultPrinter = printerService.getRepository().
                findByStoreIdAndIsDefaultAndDelFlag(printOrderVo.getStoreId(), Printer.IsDefault.DEFAULT.getCode(), CommonConstant.NORMAL_FLAG);
        //如果默认打印机为空,跳过
        if (ParamUtil.isBlank(deFaultPrinter)) {
            return;
        }
        // 菜品信息列表
        List<OrderItemVo> orderItemVos = printOrderVo.getOrderItemVoList();
        // 菜品信息列表转成默认打印机前台收银样式
        String content = PrinterUtil.getDefaultOrder(orderItemVos, 14, 6, 3, 6);
        //如果打印机为飞鹅打印机
        if (deFaultPrinter.getPrintType().equals(Printer.PrintType.FEIE.getCode())) {
            //将打印信息放入飞鹅打印定时器中
            printerRotationInit(content, deFaultPrinter.getId(), PrinterRotation.DataType.FEIE.getCode());
            return;
        }
        //将打印信息放入打印机轮训定时器中
        printerRotationInit(content, deFaultPrinter.getId(), PrinterRotation.DataType.OTHER.getCode());
    }


    //分区打印的方法
    private void areaPrint(List<OrderItemVo> orderItemVoList) {
        //过滤茶座费
        orderItemVoList = orderItemVoList.stream().filter((o) -> !o.getStatus().equals(4)).collect(Collectors.toList());

        //查找foodid对应的打印机id
        for (OrderItemVo orderItemVo : orderItemVoList) {
            AreaDetail areaDetail = areaDetailService.getRepository().findByFoodId(orderItemVo.getFoodId());
            if (ParamUtil.isBlank(areaDetail)) {
                continue;
            }
            PrintArea printArea = printAreaService.findOne(areaDetail.getPrintAreaId());
            //查询对应的打印机
            Printer printer = printerService.findOne(printArea.getPrinterId());
            //如果该菜品没有设置对应的打印机,跳过
            if (ParamUtil.isBlank(printer)) {
                continue;
            }
            orderItemVo.setPrinterId(printer.getId());
        }
        //分组
        Map<String, List<OrderItemVo>> groupByPrinter = orderItemVoList.stream().filter(o -> !ParamUtil.isBlank(o.getPrinterId())).collect(Collectors.groupingBy(OrderItemVo::getPrinterId));
        //遍历分组
        for (Map.Entry<String, List<OrderItemVo>> entryUser : groupByPrinter.entrySet()) {
            String printerId = entryUser.getKey();
            List<OrderItemVo> itemVoList = entryUser.getValue();
            // 菜品信息列表转成默认打印机前台收银样式
            String content = PrinterUtil.getAreaOrder(itemVoList, 14, 6, 3, 6);
            //查询对应的打印机
            Printer printer = printerService.findOne(printerId);
            if (printer.getPrintType().equals(Printer.PrintType.FEIE.getCode())) {
                //将打印信息放入飞鹅打印定时器中
                printerRotationInit(content, printerId, PrinterRotation.DataType.FEIE.getCode());
            } else {
                //将打印信息放入打印机轮训定时器中
                printerRotationInit(content, printerId, PrinterRotation.DataType.OTHER.getCode());
            }
        }
    }

    /*
     * @author drj
     * @date 2019-03-22 14:56
     * @Description :打印数据初始化
     */
    private void printerRotationInit(String printInfo, String printerId, Integer dataType) {
        PrinterRotation printerRotation = new PrinterRotation();
        //打印数据
        printerRotation.setPrintInfo(printInfo);
        printerRotation.setStatus(PrinterRotation.Status.UNPRINT.getCode());
        //打印机id
        printerRotation.setPrinterId(printerId);
        //打印数据类型
        printerRotation.setDataType(dataType);
        printerRotationService.save(printerRotation);
    }


    //生成签名字符串
    private static String signature(String USER, String UKEY, String STIME) {
        String s = DigestUtils.sha1Hex(USER + UKEY + STIME);
        return s;
    }
}
